package cn.wolfcode.wolf2w.redisService.impl;

import cn.wolfcode.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.domain.Store;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redisService.IStrategyStatisVOService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DateUtil;
import cn.wolfcode.wolf2w.util.JsonResult;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import jdk.nashorn.internal.scripts.JO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.dc.pr.PRError;

import java.lang.annotation.Target;
import java.rmi.server.UID;
import java.util.*;
import java.util.concurrent.TimeUnit;
//redis统计对象的服务接口
@Service
public class StrategyStatisVOServiceImpl implements IStrategyStatisVOService {
    @Autowired
    private IStrategyStatisVOService strategyStatisVOService;
    @Autowired
    private IStrategyService strategyService; //攻略访问空额老婆
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate template;
    @Override
    public void viewnumIncrease(String sid, int num) {
        //拼接vo中的key 相当于vo:sid
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        //若没有这个key就初始化操作
        //判断vo是否存在redis中
        StrategyStatisVO vo = null;
        if (!(redisTemplate.hasKey(key))){
            vo = new StrategyStatisVO();
            Strategy strategy = strategyService.get(sid);
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            vo.setViewnum(vo.getViewnum()+1);
        }else {
            //如果存在的话
            String s = redisTemplate.opsForValue().get(key);
            vo = JSON.parseObject(s, StrategyStatisVO.class);
            vo.setViewnum(vo.getViewnum()+1);

        }
        redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
    }
    //阅读数回显
    @Override
    public StrategyStatisVO findBySid(String sid) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        //判断vo对象是否存在redis中
        StrategyStatisVO vo = null;
        if (!(redisTemplate.hasKey(key))) {
            vo = new StrategyStatisVO();
            Strategy strategy = strategyService.get(sid);
            //初始化 统计数据
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
        } else {
            //如果存在的话
            String s = redisTemplate.opsForValue().get(key);
            vo = JSON.parseObject(s, StrategyStatisVO.class);

        }
     return vo;
    }
    //攻略评论数加1
    @Override
    public void replynumIncrease(String sid, int num) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        //判断vo是否存在redis中
        StrategyStatisVO vo = null;
        if (!(redisTemplate.hasKey(key))) {
            vo = new StrategyStatisVO();
            Strategy strategy = strategyService.get(sid);
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            vo.setReplynum(vo.getReplynum()+num);
        } else {
            //如果存在的话
            String s = redisTemplate.opsForValue().get(key);
            vo = JSON.parseObject(s, StrategyStatisVO.class);
            vo.setReplynum(vo.getReplynum()+num);
        }
        redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
    }
    //攻略收藏
    @Override
    public boolean favor(String sid, String id) {
        //拼接    user_strategy_favor:id id是用户id 攻略id收藏集合
        String key = RedisKeys.USER_STRATEGY_FAVORNUM.join(id);
                    //攻略id收藏集合list
                   List<String> sidList = null;
                   //判断是否存在redis中
                   if(redisTemplate.hasKey(key)) {
                       //如果已经存在了，获取
                       String sidListStr = redisTemplate.opsForValue().get(key);
                       //字符串转换成list集合，String：集合的类型
                       sidList = JSON.parseArray(sidListStr, String.class);
                   }else {
                       //攻略id收藏集合sidList不存在，并初始化
                       sidList =new ArrayList<>();
                   }
                        //判断攻略id是否在上面sidList中
                    StrategyStatisVO vo = this.findBySid(sid);
                        //创建一个boolean
                       if(sidList.contains(sid)){
                       //如果在就表示收藏过了 取消收藏 -1
                           vo.setFavornum(vo.getFavornum()-1);
                           //将id从lsit中移除
                           sidList.remove(sid);
                           //如果在就表示true 前端需要
                       }else {
                           //如果不在就表示收藏 收藏数+1
                          vo.setFavornum(vo.getFavornum()+1);
                          //add集合收藏id中
                           sidList.add(sid);
                      }
                      //更新list
                redisTemplate.opsForValue().set(key,JSON.toJSONString(sidList));
                       //更新vo
                        this.setStrategyStatisVo(vo);
                 return sidList.contains(sid);
    }

    @Override
    public List<String> strategiesFavor(String sid, String id) {
        //如果用户不为空 就new一个空的list集合出去
        if(!StringUtils.hasLength(id)){
            return Collections.EMPTY_LIST;//new Arraylist
        }
        //拼接用户收藏id
        String key = RedisKeys.USER_STRATEGY_FAVORNUM.join(id);
        //从redis中获取收藏集合
        String sidListStr = redisTemplate.opsForValue().get(key);
        //通过转化为把字符串的list1转化为集合 然后返回页面
        List<String> list = JSON.parseArray(sidListStr, String.class);
        return list;
    }

    //顶 互斥都用Boolean
    @Override
    public boolean strategyThumbup(String sid, String uid) {
        //拼接出操作记号key
        String key = RedisKeys.STRATEGY_THUMP.join(sid,uid);
        //时间
        long dateBetween = DateUtil.getDateBetween(new Date(), DateUtil.getEndDate(new Date()));
        //判断操作记号的key是否存在
        if (!redisTemplate.hasKey(key)) {
            //如果不存在,表示今天没顶过,或者已经失效了,获取vo对象 顶数+1 创建操作记号,并缓存redis中
            StrategyStatisVO vo = this.findBySid(sid);
            vo.setThumbsupnum(vo.getThumbsupnum()+1);
            //缓存记号
            redisTemplate.opsForValue().set(key, JSON.toJSONString(vo),dateBetween, TimeUnit.SECONDS);
            //缓存vo
            this.setStrategyStatisVo(vo);
            return true;
        }else {
            //如果存在表示今天已经顶过了 直接返回
            return  false;
        }
    }
    /**
     * 判断vo是否c存在redis中
     * @param id
     * @return
     */
    @Override
    public boolean isVoExsits(String id) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(id);
        return redisTemplate.hasKey(key);
    }

    /**
     * 更新vo
     * @param vo
     */
    @Override
    public void setStrategyStatisVo(StrategyStatisVO vo) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(vo.getStrategyId());
        redisTemplate.opsForValue().set(key,JSON.toJSONString(vo));

    }
    //查询vo中的所有的key
    @Override
    public List<StrategyStatisVO> findByVoAll(String pattern) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(pattern);
        //获取redis中所有某一前缀类型的key集合
        Set<String> keys = redisTemplate.keys(key);
        //通过key获取对象 添加到list集和中
        ArrayList<StrategyStatisVO> list = new ArrayList<>();
        if(keys !=null && keys.size()>0){
            for (String keyy : keys) {
                String s = redisTemplate.opsForValue().get(keyy);
                StrategyStatisVO vo = JSON.parseObject(s, StrategyStatisVO.class);
                list.add(vo);
            }
        }
        return list;
    }
    //收藏持久化
    @Override
    public void findByUid(String s) {
        String key = RedisKeys.USER_STRATEGY_FAVORNUM.join(s);
        Set<String> keys = redisTemplate.keys(key);
        for (String key1 : keys) {
            String s1 = redisTemplate.opsForValue().get(key1);
            List<String> list = JSON.parseArray(s1, String.class);
            System.err.println(111111 +""+ list);
            String substring = key1.substring(key1.indexOf(":") + 1);
            Store store = new Store();
            store.setUsid(substring);
            store.setFavors(list);
            template.save(store);
        }

    }

}
